import time
import turtle as t


def draw_square_by_corner(pen, x, y, length):
    """
    根据左上角的位置和边长画出正方形
    :return:
    """
    pen.up()
    pen.goto(x, y)
    pen.down()
    pen.setheading(0)  # 指向右
    pen.begin_fill()
    for i in range(4):
        pen.fd(length)
        pen.right(90)
    pen.end_fill()


def draw_square_by_center(pen, x, y, length):
    """
    根据中心点坐标和边长画出正方形
    :return:
    """
    new_x = x - length / 2
    new_y = y + length / 2
    draw_square_by_corner(pen, new_x, new_y, length)


def sierpinski_square(p, x, y, size, n):
    """
    递归绘制谢尔宾斯基地毯
    :param p: turtle Pen 对象
    :param x: 图案中心点x
    :param y: 图案中心点y
    :param size: 最大的正方形边长
    :param n: 迭代次数
    :return:
    """
    if n == 0:
        return
    # draw_square_by_center(p, -20 * n, n, 50 / (n + 1))
    # draw_square_by_center(p, n, -20 * n, 50 / (n + 1))
    # draw_square_by_center(p, n, 20 * n, 50 / (n + 1))
    # draw_square_by_center(p, 20 * n, n, 50 / (n + 1))
    # sierpinski_square(p, n + 1)
    move = 10 / (n * 1.5 + 2)
    move = 1
    draw_square_by_center(p, x, y, size)
    print(n)
    p.pencolor('red')
    sierpinski_square(p, x - size * move, y, size / 3, n - 1)
    p.pencolor('blue')
    sierpinski_square(p, x, y - size * move, size / 3, n - 1)
    p.pencolor('orange')
    sierpinski_square(p, x + size * move, y, size / 3, n - 1)
    p.pencolor('green')
    sierpinski_square(p, x, y + size * move, size / 3, n - 1)

    p.pencolor('brown')
    sierpinski_square(p, x - size * move, y - size * move, size / 3, n - 1)
    p.pencolor('teal')
    sierpinski_square(p, x - size * move, y + size * move, size / 3, n - 1)
    p.pencolor('orangered')
    sierpinski_square(p, x + size * move, y - size * move, size / 3, n - 1)
    p.pencolor('darkolivegreen')
    sierpinski_square(p, x + size * move, y + size * move, size / 3, n - 1)


if __name__ == '__main__':
    p = t.Pen()
    p.hideturtle()
    t.screensize(1024, 768)
    # t.delay(0)
    p.speed(0)
    a = 10
    b = 10
    l = 10
    # draw_square_by_corner(p, a, b, l)
    # draw_square_by_center(p, a, b, l)
    sierpinski_square(p, 0, 0, 200, 5)
    time.sleep(3)
